#include <stdio.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/sem.h>

union semun{
    int val;
};


int main(int argc, const char *argv[])
{
    key_t key;
    int semid;
    union semun mysem;
    struct sembuf mybuf;
    if ((key = ftok("./app", 'a')) < 0)
    {
        perror("ftok err");
        return -1;
    }

    //1创建信号灯集，参数：2代表信号灯集中信号灯的个数
    semid = semget(key, 2, IPC_CREAT | IPC_EXCL | 0666);
    if (semid < 0)
    {
        if (errno = EEXIST)
            semid = semget(key,2,0666);
        else
            {
                perror("semget err");
                return -1;
            }
    }
    //2初始化
    mysem.val = 10;
    semctl(semid,0,SETVAL,mysem);
    mysem.val = 5;
    semctl(semid,1,SETVAL,mysem);

    printf("%d\n",semctl(semid,0,GETVAL,mysem));

    //3pv操作
    //p操作，申请资源，信号量值减一
    mybuf.sem_num = 0;//编号为0的信号灯
    mybuf.sem_op = -1;//p操作
    mybuf.sem_flg = 0;//0代表阻塞
    semop(semid,&mybuf,1);

    printf("%d\n",semctl(semid,0,GETVAL,mysem));

    //4删除信号灯集
    semctl(semid,0,IPC_RMID);
    return 0;
}